package com.example.smartphonecontext;

import java.io.IOException;
import java.util.ArrayList;

import android.R.layout;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;



public class ShoutingActivity extends Activity implements OnClickListener, RecognitionListener
{
	public static final int NAME_CHANGE = 100;
	
	public String name = "";
	
	
	
	private Button nameBtn;
	private Button onBtn;
	private TextView nameText;
	private TextView powerText;
	
	private SpeechRecognizer mRecognizer;
	public static MediaPlayer mp;
	public static AudioManager ap;
	
	public Intent intent;
	
	private boolean barking;
	private static boolean power;
	
	RelativeLayout layout;

//VU8Me2tt6aR3
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.shouting);
		layout = (RelativeLayout)findViewById(R.id.shout_nickname);
		layout.setBackgroundResource(R.drawable.nickname_backgound1);	
		
		power = false;
		
		nameBtn = (Button)findViewById(R.id.nameBtn);
		nameBtn.setBackgroundResource(R.drawable.nickname_button);
		onBtn = (Button)findViewById(R.id.onBtn);
		nameText = (TextView)findViewById(R.id.nameText);
		powerText = (TextView)findViewById(R.id.powerText);
		onBtn.setVisibility(View.GONE);
		nameText.setVisibility(View.GONE);
		
		nameBtn.setOnClickListener(this);
		
		onBtn.setOnClickListener(this);
		
		
		//onBtn.setOnClickListener(this);
		
		//onBtn.setEnabled(false);
		
		
		mp = MediaPlayer.create(this, R.raw.napier_1);
		ap = (AudioManager)getSystemService(AUDIO_SERVICE);
		//mp = MediaPlayer.create(this, R.raw.Kalimba);
		
		try {
			mp.prepare();	
			
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		setPowerText();
	}
	
	public void initRecognizer(){
		if(intent == null){
			intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);            //?뚯꽦?몄떇 intent?앹꽦
			intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());    //?곗씠???ㅼ젙
			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ko-KR");                            //?뚯꽦?몄떇 ?몄뼱 ?ㅼ젙	
		}
		
//		if(mRecognizer != null){
//			mRecognizer.destroy();
//			mRecognizer = null;
//		}
		        
		mRecognizer = SpeechRecognizer.createSpeechRecognizer(this);                //?뚯꽦?몄떇 媛앹껜
		mRecognizer.setRecognitionListener(this);                                        //?뚯꽦?몄떇 由ъ뒪???깅줉
		mRecognizer.startListening(intent);
		
		
	}
	
	public void stopRecognizer(){		
		
		if(mRecognizer!= null){
		     mRecognizer.destroy();
		     mRecognizer = null;
		}		
	}
	
	private void setPowerText(){
		if(power){
			onBtn.setBackgroundResource(R.drawable.nickname_button_on);
			powerText.setText("On");
			initRecognizer();
		}else{
			onBtn.setBackgroundResource(R.drawable.nickname_button_off);
			powerText.setText("Off");
			stopRecognizer();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void onClick(View v) {
		if(v == nameBtn){
			power = false;
			setPowerText();
			Intent mintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);            //intent ?앹꽦
			mintent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());    //?몄텧???⑦궎吏?
			mintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ko-KR");                            //?뚯꽦?몄떇 ?몄뼱 ?ㅼ젙
			mintent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Give a nick name");                     //?ъ슜?먯뿉寃?蹂댁뿬 以?湲?옄

			startActivityForResult(mintent, NAME_CHANGE);                                                //援ш? ?뚯꽦?몄떇 ?ㅽ뻾
		
			
			
		}else if(v == onBtn){
			power = !power;
			setPowerText();
			Log.d("napier","buttonclick");
		}
	}	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if(requestCode == NAME_CHANGE){			
			
			
			nameBtn.setVisibility(View.GONE);
			onBtn.setVisibility(View.VISIBLE);
			onBtn.setBackgroundResource(R.drawable.nickname_button_on);
			power=true;
			setPowerText();
			layout.setBackgroundResource(R.drawable.nickname_background2);
			String key = RecognizerIntent.EXTRA_RESULTS;
			mResult = data.getStringArrayListExtra(key);        //?몄떇???곗씠??list 諛쏆븘??
			String[] result = new String[mResult.size()];            //諛곗뿴?앹꽦. ?ㅼ씠?zzz쇰줈洹몄뿉??異쒕젰?섍린 ?꾪빐
			mResult.toArray(result);                                    //    list 諛곗뿴濡?蹂?솚
	
			AlertDialog ad = new AlertDialog.Builder(this)
					.setTitle("Answer SmartPhone")
					.setSingleChoiceItems(result, -1, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									mSelectedString = mResult.get(which);
								}
							})
					.setPositiveButton("ok", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									name = mSelectedString;
									nameText.setText("" + name);
									nameText.setVisibility(View.VISIBLE);
									onBtn.setEnabled(true);
								}
							}).setNegativeButton("cancle", null).create();
			ad.show();
		}
		

		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	
	
	public ArrayList<String> mResult;
	public String mSelectedString;
	
	public void onRmsChanged(float rmsdB) {
		// TODO Auto-generated method stub
		Log.d("napier","onRmsChanged");

	}

	public void onResults(Bundle results) {
		barking = false;
		
		Log.d("napier","onResults");
		
//		// TODO Auto-generated method stub		
		mResult = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
		String[] result = new String[mResult.size()];            //諛곗뿴?앹꽦. ?ㅼ씠?쇰줈洹몄뿉??異쒕젰?섍린 ?꾪빐
		mResult.toArray(result);                                    //    list 諛곗뿴濡?蹂?솚
		
		for(int i=0; i<mResult.size(); i++){
			if (mResult.get(i).equals(name)) {
				barking = true;

				int tmpVolume = ap.getStreamVolume(AudioManager.STREAM_MUSIC);
				int maxVolume = ap.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
				ap.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.MODE_NORMAL);
				mp.start();
				ap.setStreamVolume(AudioManager.STREAM_MUSIC, tmpVolume, AudioManager.MODE_NORMAL);
//				AlertDialog ad = new AlertDialog.Builder(this);
//						.setTitle("?좏깮?섏꽭??")
//						.setPositiveButton("?뺤씤",
//								new DialogInterface.OnClickListener() {
//									@Override
//									public void onClick(DialogInterface dialog,
//											int which) {
//									}
//								})
//						.setNegativeButton("痍⑥냼",
//								new DialogInterface.OnClickListener() {
//									@Override
//									public void onClick(DialogInterface dialog,
//											int which) {
//										mSelectedString = null;
//									}
//								}).create();
//				ad.show();
			}
		}

//		//1媛??좏깮?섎뒗 ?ㅼ씠?쇰줈洹??앹꽦
//		AlertDialog ad = new AlertDialog.Builder(this).setTitle("?좏깮?섏꽭??")
//		                      .setSingleChoiceItems(result, -1, new DialogInterface.OnClickListener() {
//		                         @Override public void onClick(DialogInterface dialog, int which) {
//		                               mSelectedString = mResult.get(which);        //?좏깮?섎㈃ ?대떦 湲?옄 ??옣
//		                         }
//		                       })
//		                       .setPositiveButton("?뺤씤", new DialogInterface.OnClickListener() {
//		                          @Override public void onClick(DialogInterface dialog, int which) {
//		                                mResultTextView.setText("?몄떇寃곌낵 : "+mSelectedString);        //寃곌낵 異쒕젰
//		                           }
//		                        })
//		                       .setNegativeButton("痍⑥냼", new DialogInterface.OnClickListener() {
//		                          @Override public void onClick(DialogInterface dialog, int which) {
//		                                mResultTextView.setText("");        //痍⑥냼踰꾪듉 ?꾨Ⅴ硫?珥덇린??
//		                                mSelectedString = null;
//		                          }
//		                       }).create();
//		ad.show();
		if(barking){
			try { Thread.sleep(200); } catch (InterruptedException e) { };
		}
		
		mRecognizer.startListening(intent);
	}

	public void onReadyForSpeech(Bundle params) {
		// TODO Auto-generated method stub
		Log.d("napier","onReadyForSpeech");

	}

	public void onEndOfSpeech() {
		// TODO Auto-generated method stub
		Log.d("napier","onEndOfSpeech");

	}

	public void onError(int error) {
		// TODO Auto-generated method stub
		Log.d("napier","onError / " + error);
		initRecognizer();
	}

	public void onBeginningOfSpeech() {
		// TODO Auto-generated method stub
		Log.d("napier","onBeginningOfSpeech");

	}

	public void onPartialResults(Bundle partialResults) {
		// TODO Auto-generated method stub
		Log.d("napier","onPartialResults");

	}

	public void onEvent(int eventType, Bundle params) {
		// TODO Auto-generated method stub
		Log.d("napier","onEvent");

	}

	public void onBufferReceived(byte[] buffer) {
		// TODO Auto-generated method stub
		Log.d("napier","onBufferReceived");

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		stopRecognizer();
		super.onPause();
	}
	
	
}